package actions;

import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.NumberTermImpl;
import jason.asSyntax.Term;

import java.util.List;
import java.util.Random;

import ecomp.architecture.EcompArch;
import ecomp.models.Cell;
import ecomp.models.LocalWorldModel;

@SuppressWarnings("serial")
public class fence_end extends DefaultInternalAction{
	
	EcompArch arch;
	LocalWorldModel localWorldModel;
	
	@Override
	public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
		
		arch = (EcompArch) ts.getUserAgArch();
		localWorldModel = arch.localWorldModel;
		Term Tagx = args[0];
		Term Tagy = args[1];
		Term x = args[2];
		Term y = args[3];
		
		// Unfold terms
		int agx = (int) ((NumberTerm)Tagx).solve();
		int agy = (int) ((NumberTerm)Tagy).solve();
		int xF = -1;
		int yF = -1;
		
		List<Cell> fences = localWorldModel.getMyFences();
		
		if(fences.size() > 0){
			Cell cellBegin = new Cell(0,0,0);
			cellBegin.x = Integer.MAX_VALUE;
			cellBegin.y = Integer.MAX_VALUE;
			for(int i = 0; i < fences.size(); i++){
				Cell currentCell = fences.get(i);
				
				if((currentCell.x > cellBegin.x || currentCell.y > cellBegin.y) && localWorldModel.nearOurFence(currentCell.x,currentCell.y)){
					cellBegin = currentCell;
				}
			}
			
			if(cellBegin.x > agx){
				cellBegin.x--;
			} else {
				cellBegin.x++;
			}
			
			if(cellBegin.y > agy){
				cellBegin.y--;
			} else {
				cellBegin.y++;
			}
			xF = cellBegin.x;
			yF = cellBegin.y;
		} else {
			Random r = new Random();
			xF = r.nextInt(localWorldModel.getWidth());
			yF = r.nextInt(localWorldModel.getHeight());
		}
		un.unifies(x, new NumberTermImpl(xF));
		un.unifies(y, new NumberTermImpl(yF));

		// everything ok, so returns true
		return xF == agx && yF == agy;
	}
}